import {
  HYEventStore
} from 'hy-event-store'
import {
  getSongDetail,
  getSongLyric
} from "../service/api_music"
import {
  parseLyric
} from "../utils/parse-lyric"
// 创建播放器
// const audioContext = wx.createInnerAudioContext()
const audioContext = wx.getBackgroundAudioManager()

const playerStore = new HYEventStore({
  state: {
    isFirstPlay: true,
    // isStoping: false, // ??? 真机模拟关闭点击右侧关闭再播放重新播放

    id: 0,
    currentSong: {},
    lyricInfos: [],
    durationTime: 0,

    currentTime: 0,
    currentLyricIndex: 0,
    currentLyricText: "",

    isPlaying: false,

    // 0：循环播放  1：单曲循环  2：随机播放
    playModeIndex: 0,

    playListSongs: [],
    playListIndex: 0
  },
  actions: {
    playMusicWithSongIdAction(ctx, {
      id,
      isRefresh = false
    }) {
      if (ctx.id == id && !isRefresh) {
        this.dispatch("changeMusicPlayStatus")
        return
      }
      ctx.id = id

      // 修改播放状态
      ctx.isPlaying = true
      ctx.currentSong = {}
      ctx.durationTime = 0
      ctx.lyricInfos = []
      ctx.currentTime = 0
      ctx.currentLyricIndex = 0
      ctx.currentLyricText = ""

      // 根据id请求数据
      // 请求歌曲详情
      getSongDetail(id).then(res => {
          ctx.currentSong = res.songs[0]
          ctx.durationTime = res.songs[0].dt
          audioContext.title = res.songs[0].name
        }),
        // 请求歌词信息
        getSongLyric(id).then(res => {
          const lyricString = res.lrc.lyric
          const lyrics = parseLyric(lyricString)
          ctx.lyricInfos = lyrics
        })

      // 播放歌曲
      audioContext.stop()
      audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
      audioContext.title = id
      audioContext.autoplay = true

      // 监听播放事件
      if (ctx.isFirstPlay) {
        this.dispatch("setupAudioContextListenerAction")
        ctx.isFirstPlay = false
      }
    },
    setupAudioContextListenerAction(ctx) {
      // 监听歌曲可以播放
      audioContext.onCanplay(() => {
        audioContext.play()
      })
      // 监听时间改变
      audioContext.onTimeUpdate(() => {
        // 获取当前的时间
        const currentTime = audioContext.currentTime * 1000

        // 根据当前的时间修改currentTime
        ctx.currentTime = currentTime

        // 根据当前的时间查找播放的歌词
        if (!ctx.lyricInfos.length) return
        let i = 0
        for (; i < ctx.lyricInfos.length; i++) {
          const lyricInfo = ctx.lyricInfos[i]
          if (currentTime < lyricInfo.time) {
            break
          }
        }
        // 设置当前歌词和索引
        const currentIndex = i - 1
        if (ctx.currentLyricIndex !== currentIndex) {
          const currentLyricInfo = ctx.lyricInfos[currentIndex]
          ctx.currentLyricText = currentLyricInfo.text,
            ctx.currentLyricIndex = currentIndex
        }
      })
      // 监听歌曲播放完成
      audioContext.onEnded(() => {
        console.log("歌曲播放完，自动下一曲")
        this.dispatch("changeNewMusicAction")
      })

      // 监听音乐暂停/播放/停止
      audioContext.onPlay(() => {
        ctx.isPlaying = true
      })
      audioContext.onPause(() => {
        ctx.isPlaying = false
      })
      audioContext.onStop(() => {
        ctx.isPlaying = false
        // ctx.isStoping = true
      })
    },
    changeMusicPlayStatus(ctx, isPlaying = true) {
      ctx.isPlaying = isPlaying
      // if (ctx.isPlaying && ctx.isStoping) {
      //   audioContext.src = `https://music.163.com/song/media/outer/url?id=${ctx.id}.mp3`
      //   audioContext.title = currentSong.name
      //   audioContext.startTime = ctx.currentTime / 1000
      //   ctx.isStoping = false
      // }
      ctx.isPlaying ? audioContext.play() : audioContext.pause()
    },
    // 上一首/下一首
    changeNewMusicAction(ctx, isNext = true) {
      let index = ctx.playListIndex

      // 根据不同的播放模式，获取下一首歌的索引
      switch (ctx.playModeIndex) {
        case 0: // 0：循环播放
          index = isNext ? index + 1 : index - 1
          if (index === -1) index = ctx.playListSongs.length - 1
          if (index === ctx.playListSongs.length) index = 0
          break
        case 1: // 1：单曲循环
          break
        case 2: // 2：随机播放
          let currentIndex = Math.floor(Math.random() * ctx.playListSongs.length)
          while (ctx.playModeIndex === currentIndex) {
            currentIndex = Math.floor(Math.random() * ctx.playListSongs.length)
          }
          index = currentIndex
          break
      }
      // 获取歌曲
      let currentSong = ctx.playListSongs[index]
      if (!currentSong) {
        currentSong = ctx.currentSong
      } else {
        ctx.playListIndex = index
      }

      // 播放歌曲
      this.dispatch("playMusicWithSongIdAction", { id: currentSong.id, isRefresh: true })
    }
  }
})

export {
  audioContext,
  playerStore
}